var log = require("./../../util/loginfo").getInstand;
var gameInfo = require('./game').getInstand;
var dao = require("./../dao/dao");
var ServerInfo = require('./../config/ServerInfo').getInstand;
var crypto = require('crypto');

var serverSign = "slel3@lsl334xx,deka";

var login_api = {};

login_api.Login = function(socket, user) {

    //登录时,必须收到游戏号与房间号
    try {
        var data = JSON.parse(user);
        user = data;
        var zidunqi = true;
        if (!user.userName) {
            zidunqi = false
        }
        log.info("login", user.userName);
        if (!user.password) {
            if (!user.sign) {
                zidunqi = false
            }
        }
        if (!zidunqi) {
            log.info("用户名密码不能为空:" + JSON.stringify(user));
            return;
        }
    } catch (e) {
        log.warn('loginjson');
    }

    try {
        if (!user) {
            log.err("user is null ");
            return;
        }
        //是不是维护模式
        if (gameInfo.isMaintain()) {
            log.info("维护模式,禁止登录!");
            socket.emit("maintain", {ResultCode: 1, msg: gameConfig.maintain});
            return;
        }

        //判断是不是同一socket登录2次**********未完成还要判断每个游戏里，是否在线？以后再去改
        // if (gameInfo.isLoginAgain(socket)) {
        //     log.info("同一帐号连续登录!,必须退出一个游戏才能进入另一个游戏!");
        //     return;
        // }

        var isRobot = false
        if (user.sign == undefined) {
            var key_login = "89b5b987124d2ec3";
            var content = user.userName + user.password + key_login;
            var md5_sign = crypto.createHash('md5');
            md5_sign.update(content);
            user.password = md5_sign.digest('hex');
            user.sign = user.password;
        } else {
            isRobot = true
        }

        dao.login(user, socket, function (state, rows) {
            if (!state) {
                if (!rows) {
                    result = {resultid: 0, msg: 'Account or password error,login fail!'};
                    socket.emit('loginResult', result);
                    return
                }
                user._Robot = rows.Robot

                //数据库有此用户
                if (isRobot) {
                    if (gameInfo.IsPlayerOnline(rows.Id)) {
                        log.info(`用户在线,进入等待离线列队 user ${rows.Id}`);
                        user.id = rows.Id;
                        user.socket = socket;
                        user.userName = rows.Account;
                        user.headimgurl = rows.headimgurl;
                        //加入登录列队
                        gameInfo.addLoginList(user);
                        return
                    }
                }
                gameInfo.addUser(rows, socket, function (result) {
                    if (result == 1) {   //断线从连
                        gameInfo.lineOutSet({userId: user.id})
                    }
                });
            } else if (state == 1) {
                var result = {};
                result = {resultid: 0, msg: 'Account or password error,login fail!'};
                socket.emit('loginResult', result);
                log.info("登录失败!");
            } else if (state == 2) {
                var result = {};
                result = {resultid: -1, msg: 'This account is disabled!'};
                socket.emit('loginResult', result);
                log.info("登录失败,帐号被停用!");
            }
        })
    } catch (error) {
        log.err(error);
    }
}
  
login_api.LoginGame = async function(socket, _userinof) {
    try {
        if (_userinof.serverSign == serverSign) {
            //让这个用户进入该游戏
            log.info("LoginGame " + _userinof.userid)
            var encoin = ServerInfo.getServerEnterCoinByProt(_userinof.serverId);
            log.info("LoginGame2 " + _userinof.userid)
            var userInfo = await gameInfo.LoginGame(_userinof.userid, _userinof.sign, _userinof.serverId, encoin);
            var result = {};
            if (userInfo._userId) {
                result = {ResultCode: 1, userInfo: userInfo};
                var info = {
                    state: 1,
                    gameId: _userinof.gameId,
                    serverId: _userinof.serverId,
                    userId: _userinof.userid,
                    tableId: -1,
                    seatId: -1
                };
                gameInfo.lineOutSet(info);
            } else {
                result = {ResultCode: 0, userid: _userinof.userid, msg: userInfo.msg};
            }
            log.info("用户进入房间 " + _userinof.userid)
            socket.emit('LoginGameResult', result);
            log.info("test7 发送登录的游戏 " + result.ResultCode);
        }
    } catch (error) {
        log.err(error);
    }
}

login_api.LoginClub = function(socket, _userinof) {
    try {
        if (_userinof.serverSign != serverSign) {
            log.err("user sign is incorrect! ", _userinof.serverSign);
            return;
        }

        //让这个用户进入该游戏
        //log.info(_userinof)
        var encoin = ServerInfo.getServerEnterCoinByProt(_userinof.serverId);
        var userInfo = gameInfo.LoginGame(_userinof.userid, _userinof.sign, _userinof.serverId, encoin);
        var result = {};
        if (userInfo._userId) {
            var result = {ResultCode: 1, userInfo: userInfo};
            // var info = {
            //     state: 1,
            //     gameId: _userinof.gameId,
            //     serverId: _userinof.serverId,
            //     userId: _userinof.userid,
            //     tableId: -1,
            //     seatId: -1
            // };
            // gameInfo.lineOutSet(info);
        } else {
            var result = {ResultCode: 0, userid: _userinof.userid, msg: userInfo.msg};
        }
        socket.emit('LoginClubResult', result);
    } catch (error) {
        log.err(error);
    }
}

module.exports = login_api;